package com.mm.cloud.gateway.filter;

import com.mm.cloud.common.redis.constant.RedisKeySystemConstants;
import com.mm.cloud.common.redis.service.IRedisService;
import com.mm.cloud.common.redis.util.RedisKeyStringUtils;
import com.mm.cloud.common.core.constant.SecurityConstants;
import com.mm.cloud.common.core.enums.ExceptionEnum;
import com.mm.cloud.common.core.exception.BaseException;
import com.mm.cloud.gateway.filter.white.IgnoreWhiteProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 登录认证过滤器
 *
 * @author mr
 * @since 2023-04-05
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private IgnoreWhiteProperties ignoreWhite;

    @Autowired
    private IRedisService redisService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        //判断白名单
        String url = request.getURI().getPath();
        if (ignoreWhite.matches(url)) {
            return chain.filter(exchange);
        }
        //判断token有效性
        final String token = getToken(request);
        if (StringUtils.isEmpty(token)) {
            throw new BaseException(ExceptionEnum.TOKEN_INVALID);
        }
        Object o = redisService.get(RedisKeyStringUtils.appendRedisKey(RedisKeySystemConstants.REDIS_TOKEN, token));
        if (ObjectUtils.isEmpty(o)) {
            throw new BaseException(ExceptionEnum.TOKEN_INVALID);
        }
        //执行过滤器链
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 获取token
     */
    public static String getToken(ServerHttpRequest request) {
        return request.getHeaders().getFirst(SecurityConstants.SECURITY_TOKEN);
    }

}
